<?php
/**
 * Created by PhpStorm.
 * User: Jiawei
 * Date: 2017/7/29
 * Time: 19:06
 */

namespace App\Lib\WeApp\Api;


use App\Jobs\Order\OrderDeliverInfoManage;
use App\Jobs\Shop\ShopOrderDeliverInfoManage;
use App\Models\Shop\WxShopOrder;
use App\Models\Shop\WxShopOrderCoupon;
use App\Models\User\WxUser;
use App\Models\WxOrder;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\OrderUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\ShopUtils;
use App\Wen\Utils\StrUtils;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class DeliverInfoManage extends BaseApi
{
    public function isNeed(){
        $url = ApiUrl::DELIVER_INFO_MANAGE_NEED;
        $param = array(
            'appid' => Settings::get('app_id', '')
        );
        try {
            $res = $this->sendRequestWithToken($url,$param);
            if($res && _array_key($res, 'errcode', -1) === 0){
                return _array_key($res, 'is_trade_managed', false);
            }
        }catch (\Exception $e){
            return false;
        }
        return false;
    }

    public function getDeliverOrder($transaction_id){
        $url = ApiUrl::DELIVER_INFO_MANAGE_GET_ORDER;
        $param = array(
            'transaction_id' => $transaction_id
        );
        try {
            $res = $this->sendRequestWithToken($url,$param);
            if($res && _array_key($res, 'errcode', -1) === 0){
                return _array_key($res, 'order', []);
            }
        }catch (\Exception $e){
            _logger_(__file__, __line__, $e->getMessage());
            return null;
        }
    }

    public function selfPickUp(WxShopOrder &$shopOrder, $scanner){
        if(_empty_($shopOrder)){
            return;
        }
        if($shopOrder->pay_status != 2 || $shopOrder->status != 1){
            return;
        }
        $url = ApiUrl::DELIVER_INFO_MANAGE_UPLOAD;
        $param = array(
            'order_key' => [
                'order_number_type' => 2,
                'transaction_id' => $shopOrder->serial_number
            ],
            'logistics_type' => 4,
            'delivery_mode' => 'UNIFIED_DELIVERY',
            'is_all_delivered' => true,
            'shipping_list' => [
                [
                    'item_desc' => StrUtils::limit(ShopUtils::get_order_item_desc($shopOrder), 20),
                ]
            ],
            'upload_time' => Carbon::now()->toRfc3339String(),
            'payer' => [
                'openid' => WxUser::where('id', $shopOrder->user_id)->value('weixin_openid')
            ]
        );

        try {
            // 尝试发货
            $upload_res = $this->sendRequestWithToken($url,$param);
            if($upload_res && _array_key($upload_res, 'errcode', -1) === 0){
                $wechat_order = $this->getDeliverOrder($shopOrder->serial_number);
                if($wechat_order){
                    if(in_array(_array_key($wechat_order, 'order_state', 0), [2,3,4])){
                        WxShopOrder::where('id', $shopOrder->id)->update([
                            'status' => 8
                        ]);
                        WxShopOrderCoupon::where('order_id', $shopOrder->id)->update([
                            'scanner' => $scanner,
                            'scan_at' => current_time()
                        ]);
                        GatewayUtils::success(GatewayUtils::uid2client_id($shopOrder->user_id), 19, [
                            'transaction_id' => $shopOrder->serial_number
                        ]);
                    }
                }
            }else{
                ShopOrderDeliverInfoManage::dispatch('upload', $shopOrder->id, $scanner)->delay(now()->addSeconds(40));
            }
        }catch (\Exception $e){
            if($e->getCode() == 10060001){
                // 10060001:支付单不存在
                ShopOrderDeliverInfoManage::dispatch('upload', $shopOrder->id, $scanner)->delay(now()->addSeconds(10));
            }else if($e->getCode() == 10060004){
                $wechat_order = $this->getDeliverOrder($shopOrder->serial_number);
                if($wechat_order){
                    if(in_array(_array_key($wechat_order, 'order_state', 0), [3,4])){
                        if(ShopUtils::coupon_to_finish($shopOrder, $scanner, '')){
                            GatewayUtils::success(GatewayUtils::uid2client_id($scanner), 17);
                            GatewayUtils::success(GatewayUtils::uid2client_id($shopOrder->user_id), 17);
                        }
                    }
                }
            }else{
                _logger_(__file__, __line__, $e->getMessage());
            }
        }
    }


    public function virtualDeliverShopOrder(WxShopOrder &$shopOrder){
        if(_empty_($shopOrder)){
            return;
        }

        if($shopOrder->status != 9){
            return;
        }

        $url = ApiUrl::DELIVER_INFO_MANAGE_UPLOAD;
        $param = array(
            'order_key' => [
                'order_number_type' => 2,
                'transaction_id' => $shopOrder->serial_number
            ],
            'logistics_type' => 3,
            'delivery_mode' => 'UNIFIED_DELIVERY',
            'is_all_delivered' => true,
            'shipping_list' => [
                [
                    'item_desc' => StrUtils::limit(ShopUtils::get_order_item_desc($shopOrder), 20),
                ]
            ],
            'upload_time' => Carbon::now()->toRfc3339String(),
            'payer' => [
                'openid' => WxUser::where('id', $shopOrder->user_id)->value('weixin_openid')
            ]
        );

        try {
            // 尝试发货
            $upload_res = $this->sendRequestWithToken($url,$param);
            if($upload_res && _array_key($upload_res, 'errcode', -1) === 0){
                $wechat_order = $this->getDeliverOrder($shopOrder->serial_number);
                if($wechat_order){
                    if(in_array(_array_key($wechat_order, 'order_state', 0), [2,3,4])){
                        WxShopOrder::withTrashed()->where('id', $shopOrder->id)->update([
                            'status' => 10
                        ]);
                        GatewayUtils::success(GatewayUtils::uid2client_id($shopOrder->user_id), 19, [
                            'transaction_id' => $shopOrder->serial_number
                        ]);
                    }
                }
            }else{
                ShopOrderDeliverInfoManage::dispatch('virtual-upload', $shopOrder->id, null)->delay(now()->addSeconds(40));
            }
        }catch (\Exception $e){
            if($e->getCode() == 10060001){
                // 10060001:支付单不存在
                OrderDeliverInfoManage::dispatch('virtual-upload', $shopOrder->id)->delay(now()->addSeconds(10));
            }else if($e->getCode() == 10060004){
                $wechat_order = $this->getDeliverOrder($shopOrder->serial_number);
                if($wechat_order){
                    if(in_array(_array_key($wechat_order, 'order_state', 0), [3,4])){
                        DB::beginTransaction();
                        try {
                            // todo:

                            $ship_at = date('Y-m-d H:i:s', time());
                            WxShopOrder::withTrashed()->where('id', $shopOrder->id)->update([
                                'has_virtual' => 1,
                                'ship_at' => $ship_at,
                                'status' => 2,
                            ]);
                            ShopUtils::paied_content_process($shopOrder->id);

                            DB::commit();
                            return;
                        } catch (\Exception $e) {
                            DB::rollBack();
                            _logger_(__file__, __line__, $e->getMessage());
                            return;
                        }

                    }
                }
            }else{
                _logger_(__file__, __line__, $e->getMessage());
            }
        }

    }

    /**
     * 普通订单的虚拟发货
     * @param WxOrder $order
     */
    public function virtualDeliverOrder(WxOrder &$order){
        if(_empty_($order)){
            return;
        }
        if($order->order_state != 3){
            return;
        }
        $url = ApiUrl::DELIVER_INFO_MANAGE_UPLOAD;
        $param = array(
            'order_key' => [
                'order_number_type' => 2,
                'transaction_id' => $order->order_serial_number
            ],
            'logistics_type' => 3,
            'delivery_mode' => 'UNIFIED_DELIVERY',
            'is_all_delivered' => true,
            'shipping_list' => [
                [
                    'item_desc' => StrUtils::limit($order->order_information, 20),
                ]
            ],
            'upload_time' => Carbon::now()->toRfc3339String(),
            'payer' => [
                'openid' => WxUser::where('id', $order->user_id)->value('weixin_openid')
            ]
        );

        try {
            // 尝试发货
            $upload_res = $this->sendRequestWithToken($url,$param);
            if($upload_res && _array_key($upload_res, 'errcode', -1) === 0){
                $wechat_order = $this->getDeliverOrder($order->order_serial_number);
                if($wechat_order){
                    if(in_array(_array_key($wechat_order, 'order_state', 0), [2,3,4])){
                        WxOrder::where('id', $order->id)->update([
                            'order_state' => 5
                        ]);
                        GatewayUtils::success(GatewayUtils::uid2client_id($order->user_id), 19, [
                            'transaction_id' => $order->order_serial_number
                        ]);
                    }
                }
            }else{
                OrderDeliverInfoManage::dispatch('upload', $order->id)->delay(now()->addSeconds(40));
            }
        }catch (\Exception $e){
            if($e->getCode() == 10060001){
                // 10060001:支付单不存在
                OrderDeliverInfoManage::dispatch('upload', $order->id)->delay(now()->addSeconds(10));
            }else if($e->getCode() == 10060004){
                $wechat_order = $this->getDeliverOrder($order->order_serial_number);
                if($wechat_order){
                    if(in_array(_array_key($wechat_order, 'order_state', 0), [3,4])){
                        DB::beginTransaction();
                        try {
                            // todo:
                            WxOrder::where('id', $order->id)->update([
                                'order_state' => 1
                            ]);
                            $order = WxOrder::find($order->id);
                            OrderUtils::order_obtains($order, 0);
                            DB::commit();
                            return;
                        } catch (\Exception $e) {
                            DB::rollBack();
                            _logger_(__file__, __line__, $e->getMessage());
                            return;
                        }

                    }
                }
            }else{
                _logger_(__file__, __line__, $e->getMessage());
            }
        }
    }
}
